package cn.tedu.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

//@Component
public class My02Filter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入我的第二个过滤器");
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取uri相关信息
        URI uri = request.getURI();
        System.out.println("获取到请求uri:" + uri);
        String path = uri.getPath();
        System.out.println("获取请求的path:" + path);
        String host = uri.getHost();
        System.out.println("获取请求的host:" + host);
        String query = uri.getQuery();
        System.out.println("获取请求的query:" + query);
        int port = uri.getPort();
        System.out.println("获取请求的port:" + port);
        //3.获取query数据
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //进行逻辑判断
        if (!queryParams.isEmpty()) {
            if (queryParams.containsKey("name")) {
                List<String> names = queryParams.get("name");
                if (!CollectionUtils.isEmpty(names)) {
                    System.out.println("query中包含的name");
                    System.out.println("query中name对应的value值：" + names);
                }
            }
        }
        //4.获取请求头
        HttpHeaders headers = request.getHeaders();
        List<String> authorizations = headers.get("Authorization");
        if (!CollectionUtils.isEmpty(authorizations)) {
            System.out.println("请求头中包含的authorization");
            System.out.println("authorization对应的value值：" + authorizations);
        }
        //5.获取请求cookie
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        if (!cookies.isEmpty()) {
            //测试一个自定义的token
            if (cookies.containsKey("token")) {
                List<HttpCookie> token = cookies.get("token");
                if (!CollectionUtils.isEmpty(token)) {
                    System.out.println("请求中包含的token");
                    System.out.println("token对应的value值：" + token);
                }
            }
        }
        return chain.filter(exchange); //让这个请求正常通过
    }

    @Override
    public int getOrder() {
        return 0; //数字越小，顺序越靠前
    }
}
